package com.gykfbxxh.imovie.manager;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.utils.util.AppTools;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.bean.info.UserInfor;
import com.gykfbxxh.imovie.bean.info.UserInforBean;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.net.ParamMap;
import com.gykfbxxh.imovie.greendao.GDManager;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.utils.DialogUtils;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.view.user.activity.WebActivity;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

/**
 * Created by Guo on 2016/7/13.
 * <p>
 * 用户信息的管理类:
 */
public class UserInforManager extends Observable implements View.OnClickListener {
    private static UserInforManager mUserInforManager;

    private UserInfor userInfor;//用户信息类
    private UserInfor netUserInfor;//网络临时用户

    private String mPageName;
    private Intent mIntentLogin;

    public static final int TO_LOGIN_REQUESTCODE = 190;
    private Activity activity;

    private UserInforManager() {
        this.mPageName = "UserInforManager";
    }


    /**
     * 数据更改时候的通知,必须调用setChanged之前在调用notifyObservers()
     */
    public void dataChanged() {
        setChanged();
        notifyObservers();
    }


    public static UserInforManager getInstance() {
        if (mUserInforManager == null) {
            mUserInforManager = new UserInforManager();
        }
        return mUserInforManager;
    }

    /**
     * 此方法来判断用户是否登录,返回为true,则表明userinfor和task均不为空
     *
     * @return
     */
    public boolean isLogin() {
        if (this.userInfor != null && !TextUtils.isEmpty( userInfor.getfUsername())) {
            return true;
        }
        userInfor = null ;
        return false;
    }

    /**
     * 设置用户信息
     *
     * @param userInfor
     */
    public void setUserInfor(UserInfor userInfor) {
        this.userInfor = userInfor;
    }

    /**
     * 设置网络临时用户
     *
     * @param netUserInfor
     */
    public void setNetUserInfor(UserInfor netUserInfor) {
        this.netUserInfor = netUserInfor;
    }

    /**
     * 拿取用户信息,如果内存中没有,则会拿取数据库中的
     *
     * @return
     */
    public UserInfor getUserInfor() {
        //拿取本地存储的->c
        if (userInfor == null) {
            userInfor = GDManager.getInstance().getUserInfoFromGD();
        }
        return userInfor;
    }


    /**
     * 本地登录/伪登录
     *
     * @return
     */
    public void localWeiLogin(final Context context) {
        if (getUserInfor() != null) {
            UserInfor userInfor = getUserInfor();
            if(!TextUtils.isEmpty(userInfor.getfPhone())) {
                SharedPreferences configSP = AppConfigManager.getInstance().getConfigSP();
                String userpwd = configSP.getString(ConfigKey.USERPWD, "");
                if(TextUtils.isEmpty(userpwd)) {
                    GDManager.getInstance().delUserInfoGD();
                    setUserInfor(null);
                    AppConfigTools.TOKENSTR = "";
                    return;
                }
                //请求伪登录
                ParamMap params = new ParamMap();
                params.putEncode("phone", userInfor.getfPhone());
                params.putEncode("password", userpwd);
                params.putEncode("loginapp", "4");
                //加密
                //HttpUtils.ParmsMD5Encryption(params);
                HttpUtils.ParmsMapMD5(params);

                addPostRequest(URIContant.LOGINUSER, new TypeToken<UserInforBean>() {
                }.getType(), params, new HttpListener<UserInforBean>() {
                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onSuccess(UserInforBean response) {//成功了
                        if(response!=null&&"LoginSucess".equals(response.getCode())&&response.getResult()!=null) {
                            UserInfor userInfor = response.getResult();
                            //设置用户信息
                            UserInforManager.getInstance().setUserInfor(userInfor);//设置用户信息
                            //保存到本地
                            UserInforManager.getInstance().saveUserInfor(userInfor);
                        }
                    }
                });
            }else {
                //走快捷登录
            }

        }
    }



    /**
     * 是否展示 评分弹窗的逻辑前置方法
     * @param context
     */
    private void isShowMarketDialog(Activity context) {
        String s = AppConfigManager.getInstance().readConfig(ConfigKey.isShow_marketdialog, "");
        if(TextUtils.isEmpty(s)){//第一次
            ToastUtils.cancelToast();
            goToMarketDialog(context);
        }else{
            String[] split = s.split("_");
            if(split != null && split.length == 2){
                if(!TextUtils.equals(AppTools.getVersionName(),split[1])
                        && !Boolean.valueOf(split[0])){
                    ToastUtils.cancelToast();
                    goToMarketDialog(context);
                }
            }
        }
    }


    /**
     * 显示 评分的dialog
     */
    private void goToMarketDialog(Activity activity) {
        this.activity = activity;
        View marketDialog = LayoutInflater.from(activity).inflate(R.layout.dialog_market, null);
        TextView tvOk = (TextView) marketDialog.findViewById(R.id.tv_ok);
        TextView tvRefuse = (TextView) marketDialog.findViewById(R.id.tv_refuse);
        TextView tvCancel = (TextView) marketDialog.findViewById(R.id.tv_cancel);
        tvOk.setOnClickListener(this);
        tvRefuse.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        HashMap<String, Object> dialogParams = new HashMap<>();
        dialogParams.put("width", 300);
        DialogUtils.getInstance().showCDialog(marketDialog, activity, dialogParams);

        AppConfigManager.getInstance().writeConfig(ConfigKey.isShow_marketdialog, "true_"+ AppTools.getVersionName());
    }


    /**
     * 保存UserInfor至本地
     * 更新如果失败,表示没有,就插入一条
     *
     * @param userInfor
     */
    public void saveUserInfor(UserInfor userInfor) {
        if (userInfor == null||TextUtils.isEmpty(userInfor.getfUsername())) return;

        GDManager.getInstance().insertOrReplaceUserInforData(userInfor);
    }


    /**
     * 跳转web页面
     *
     * @param title
     * @param url
     */
    public void toWebActivity(Activity mActivity, String title, String url) {

        try {
            Intent intent = new Intent(mActivity, WebActivity.class);
            intent.putExtra("title", title);
            intent.putExtra("url", url);
            mActivity.startActivity(intent);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到登录页面
     *
     * @param actvity
     */

    public void toLoginPage(Activity actvity) {
//        if (actvity == null || actvity.isFinishing()) {
//            return;
//        }
//        if (!AppManager.getAppManager().isHaveActivity(QuickLoginActivity.class)) {
//            if (mIntentLogin == null) {
//                mIntentLogin = new Intent(actvity, QuickLoginActivity.class);
//            }
//            actvity.startActivityForResult(mIntentLogin, TO_LOGIN_REQUESTCODE);
//            actvity.overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
//        }

    }



    /**
     * 获取用户的加密的手机
     *
     * @return
     */
//    public String getJiamiPhone() {
//        if(getUserInfor() == null){
//            return "";
//        }
//        String phone = getUserInfor().getfPhone();
//        String jiamiphone = getUserInfor().getfPassword();
//
//        if (TextUtils.isEmpty(phone)) {
//            return "";
//        }
//
//        if (TextUtils.isEmpty(jiamiphone)) {// 为空,进行加密
//            if (phone.length() < 6) {
//                jiamiphone = phone;
//                return jiamiphone;
//            }
//            String phone1 = phone.substring(0, 3);
//            String phone2 = phone.substring(phone.length() - 2);
//            String phone3 = phone.substring(3, phone.length() - 2);
//            String phone4 = "";
//            for (int i = 0; i < phone3.length(); i++) {
//                phone4 += "*";
//            }
//            jiamiphone = (phone1 + phone4 + phone2);
//            return jiamiphone;
//        } else {// 判断后两位
//
//            String phoneLast2 = "";
//            String jiamiPhoneLast2 = "";
//            try {
//                phoneLast2 = phone.substring(phone.length() - 2,
//                        phone.length());
//                jiamiPhoneLast2 = jiamiphone.substring(
//                        jiamiphone.length() - 2, jiamiphone.length());
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            if (TextUtils.equals(phoneLast2, jiamiPhoneLast2)) {
//                return jiamiphone;
//            } else {
//                if (phone.length() < 6) {
//                    jiamiphone = phone;
//                    return jiamiphone;
//                }
//                String phone1 = phone.substring(0, 3);
//                String phone2 = phone.substring(phone.length() - 2);
//                String phone3 = phone.substring(3, phone.length() - 2);
//                String phone4 = "";
//                for (int i = 0; i < phone3.length(); i++) {
//                    phone4 += "*";
//                }
//                jiamiphone = (phone1 + phone4 + phone2);
//                return jiamiphone;
//            }
//        }

//    }


    protected void addPostRequest(@NonNull String url, @NonNull Type type, Map<String, String> parms, @NonNull HttpListener<?> httpListener) {

        HttpUtils.addPostRequest(url, type, mPageName, parms, httpListener);
    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_ok:

                Uri uri = Uri.parse("market://details?id=" + activity.getPackageName());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    activity.startActivity(intent);
                    activity.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
                } catch (ActivityNotFoundException e) {
                    ToastUtils.showText("没有检测到任何电子市场,无法评分");
                }
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.tv_refuse:
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.tv_cancel:
                DialogUtils.getInstance().dismissCDialog();
                break;
        }
    }
}
